package com.lsh.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class MailUtil {
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to,String subject,String text){
        try {
            //创建一个邮件mimeMessage,它封装了我们要发送的邮箱的相关内容
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //通过helper向邮件mimeMessage里写内容
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);//设置发送对象，这个对象是我们在配置文件中配置的对象
            helper.setTo(to);//设置接收对象
            helper.setSubject(subject);//设置邮件标题
            //添加邮件的主题内容，设置true,支持html文件类型
            helper.setText(text,true);
            //将创建的邮件发送出去
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

}
